package com.movitech.mobile.cz.base.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.movitech.mobile.cz.base.common.spring.SpringContextHolder;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.sessionuser.SessionUserService;
import com.movitech.mobile.cz.base.sessionuser.SessionUserVo;

public class SessionUserFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
		Gson gson = new Gson();
		boolean isExpired = false;
		try {
			SessionUserService sessionUserService = (SessionUserService)SpringContextHolder.getBean("sessionUserService");
			SessionUserVo userVo = sessionUserService.getSessionUser();
			if(userVo == null) {
				isExpired = true;
			}
		} catch (Exception e) {
			isExpired = true;
		}
		if(isExpired) {
			response.getWriter().write(gson.toJson(new RestReturnResult<Object>(CommonConstants.FAIL,"user is expired")));
			return;
		}else {
			filterChain.doFilter(request, response);
		}
	}

	/*   
	springboot注册方式
	@Bean
    public FilterRegistrationBean filterTokenFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        //注入过滤器
        registration.setFilter(new TokenFilter());
        //拦截规则
        registration.addUrlPatterns("/*");
        //过滤器名称
        registration.setName("TokenFilter");
        //过滤器顺序
        registration.setOrder(1);
        return registration;
    }
    */
    
}
